package com.zmc.member.infrastructure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.member.infrastructure.bean.query.MyCollectionQuery;
import com.zmc.member.infrastructure.entity.MemberCollectEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmc.common.utils.PageUtils;
import com.zmc.common.utils.Query;

import com.zmc.member.infrastructure.dao.MemberCollectDao;
import com.zmc.member.infrastructure.service.MemberCollectService;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author zmc
 */
@Service("memberCollectSpuService")
public class MemberCollectServiceImpl extends ServiceImpl<MemberCollectDao, MemberCollectEntity> implements MemberCollectService {

    @Autowired
    private AuthTokenService authTokenService;
    @Override
    public PageUtils queryPage(MyCollectionQuery query) {
        Page<MemberCollectEntity> page = baseMapper.selectPage(new Page<>(query.getPageNum(), query.getPageSize()), getWrapper(query));
        List<String> list = page.getRecords().stream().map(MemberCollectEntity::getSkuId).collect(Collectors.toList());
        return new PageUtils(list, page.getTotal(), page.getSize(), page.getCurrent());
    }

    @Override
    @Transactional
    public void saveBySku(String skuId) {
        if (containsSku(skuId)) {
            return;
        }
        MemberCollectEntity entity = new MemberCollectEntity();
        entity.setMemberId(authTokenService.getMemberInfo().getMemberId());
        entity.setSkuId(skuId);
    }

    @Override
    @Transactional
    public void removeBySku(String skuId) {
        baseMapper.removeBySku(authTokenService.getMemberInfo().getMemberId(), skuId);
    }

    @Override
    public boolean containsSku(String skuId) {
        LambdaQueryWrapper<MemberCollectEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberCollectEntity::getMemberId, authTokenService.getMemberInfo().getMemberId())
                .eq(MemberCollectEntity::getSkuId, skuId);
        return getOne(wrapper) != null;
    }

    private LambdaQueryWrapper<MemberCollectEntity> getWrapper(MyCollectionQuery query) {
        LambdaQueryWrapper<MemberCollectEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberCollectEntity::getMemberId, authTokenService.getMemberInfo().getMemberId())
                .orderByDesc(MemberCollectEntity::getCreateTime);
        return wrapper;
    }

}